//
//  ZPNewPasswordViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/2.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPUpdateSetPwdViewController.h"
#import "ZPRegisterLoginViewController.h"
#import "NSString+Emoji.h"
@interface ZPUpdateSetPwdViewController ()
{
    MBProgressHUD *hud;
}
// 输入新密码
@property (weak, nonatomic) IBOutlet UITextField *NewPwd;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;

@end

@implementation ZPUpdateSetPwdViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.NewPwd.secureTextEntry = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
    _doneBtn.enabled=NO;
    _doneBtn.backgroundColor = UIColorFromRGB(0x999999);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditing) name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


- (void)dismissKeyboard
{
    [self.NewPwd resignFirstResponder];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    self.title = @"设置新密码";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackButtonItem)];
}
- (void)clickBackButtonItem
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)textFieldDidEndEditing{
    if (_NewPwd.text.length) {
        _doneBtn.enabled=YES;
        _doneBtn.backgroundColor = UIColorFromRGB(0x21A4EB);
    }else{
        _doneBtn.enabled=NO;
        _doneBtn.backgroundColor = UIColorFromRGB(0x999999);
    }
}


#pragma mark - <密码是否可见>
- (IBAction)isShowPwdButtonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.NewPwd.secureTextEntry = !sender.selected;
}



- (IBAction)completeBtnClick:(UIButton *)sender
{
    NSString *password = self.NewPwd.text;
    if (password.length < 6 || password.length > 20) {
        [ZPPromptView showMessage:@"密码长度必须6~20位"];
        return;
    }
    
    if ([password containsString:@" "]||[password containsEmoji]) {
        [ZPPromptView showMessage:@"密码不能包含特殊字符或空格"];
        return;
    }
    
    hud.hidden = NO;
    NSDictionary *params = @{@"teacherId":[[ZPAuthStore sharedZPAuthStore].userToDic  objectForKey:@"memberId"],
                             @"mobile":[[ZPAuthStore sharedZPAuthStore].userToDic  objectForKey:@"mobile"],
                             @"password":[password zp_md5String],
                             @"idfv":[[ZPAuthStore  sharedZPAuthStore].userToDic objectForKey:@"deviceID"]};
    [[ZPNetworking sharedZPNetworking] POST:APIPPT@"access/updateUserPassWordByTeacher.json" parameters:params progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        hud.hidden = YES;
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            [ZPPromptView showMessage:@"修改密码成功"];
            NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
            NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
            if (!dataDic) {
                dataDic = [NSMutableDictionary dictionary];
            }
            [dataDic setObject:self.NewPwd.text forKey:@"passwd"];
            
            NSDictionary  *tempDic = responseObject[@"result"];
            NSString  *tokenStr = @"";
            if ([tempDic  objectForKey:@"access_token"] && ![[tempDic  objectForKey:@"access_token"] isEqual:[NSNull  null]]) {
                tokenStr = [tempDic  objectForKey:@"access_token"];
            }
            [dataDic setValue:tokenStr forKey:@"token"];
            
            [dataDic writeToFile:homePath atomically:YES];
            [[ZPAuthStore  sharedZPAuthStore] resetUserInfoDictionary];
            [[ZPAuthStore sharedZPAuthStore] setWebViewCookiesWithType:1];
            
            if ([NSStringFromClass([[self.navigationController.viewControllers firstObject] class]) isEqualToString:NSStringFromClass([ZPRegisterLoginViewController class])]) {
                [self performSelector:@selector(pullDownVC) withObject:nil afterDelay:1.0];
            }else{
                [self performSelector:@selector(backToRoot) withObject:nil afterDelay:1.0];
            }
        }
        else {
            [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
        }
    } failure:^(NSError * _Nonnull error) {
        hud.hidden = YES;
        [ZPPromptView showMessage:@"请检查您的网络设置"];
    }];
    
//    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)pullDownVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)backToRoot
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
